package main

import (
	"fmt"
	"net"
	"study/14_practice_chat/processor"
	"study/14_practice_chat/utils"
)

func handleConnection(conn net.Conn) {
	// defer conn.Close()
	var serverProcessor processor.ServerProcessor = processor.ServerProcessor{
		Conn: conn,
	}
	for {
		request, err := utils.ReadRequest(conn)
		if err != nil {
			fmt.Println("读请求体异常！", err)
			return
		}
		fmt.Println(request)
		fmt.Printf("reques类型=%T \n", request)
		// 返回响应
		// response := common.ResponseBody{
		// 	Code:     200,
		// 	Msg:      "success",
		// 	DataType: "response type",
		// 	Data:     "response data",
		// }
		// err = utils.WriteResponse(conn, response)
		// if err != nil {
		// 	fmt.Println("写响应异常！", err)
		// 	return
		// }
		err = serverProcessor.Processor(request)
		if err != nil {
			fmt.Println("processor failure!", err)
		} else {
			fmt.Println("processor success!")
			break
		}
	}
	return
}

func main() {

	ln, err := net.Listen("tcp", ":8080")
	if err != nil {
		fmt.Println("监听失败，", err)
	}
	fmt.Println("服务端【127.0.0.1:8080】启动成功！")
	defer ln.Close()

	for {
		conn, err := ln.Accept() // 阻塞等待连接进来
		if err != nil {
			// handle error
			fmt.Println("获得连接失败，", err)
			continue
		}
		go handleConnection(conn)
	}

}
